<template>
  <div class="logic-config">
    <ContentWrap>
      <FormContainer :column="3">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px" @submit.native.prevent>
          <el-form-item prop="combinationCode" label="因子">
            <SelectForDict :code.sync="formData.combinationCode" dict-type-code="FACTOR_PROPERTY" placeholder="请选因子" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item prop="combinationName" label="因子名称">
            <el-input v-model="formData.combinationName" placeholder="请输入因子名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="优先级" prop="level" hidden>
            <el-input v-model="formData.level" clearable placeholder="请输入优先级"></el-input>
          </el-form-item>
          <el-form-item prop="state" label="启用状态">
            <SearchSelectPicker
              placeholder="请选择启用状态"
              lable-name="dictName"
              value-name="dictCode"
              :select-data="enableList"
              :value.sync="formData.state"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="createTime" label="创建时间">
            <el-date-picker
              v-model="formData.createTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              opt
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item more show>
            <Button @click="resetForm">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div>
        <AddOrEdit @on-refresh="handleRefresh"></AddOrEdit>
        <AddOrEdit is-edit :selection="selection" @on-refresh="handleRefresh"></AddOrEdit>
        <Button type="primary" @click="handleUpdateEnable(1)">启用</Button>
        <Button type="primary" @click="handleUpdateEnable(0)">停用</Button>
        <Button type="primary" @click="handleRemove">删除</Button>
      </div>
      <table-box ref="tableBox" show-selection show-index no-request :other-filters="filtersRaw" :selected-arry.sync="selection" :table-config="tableConfig" @selection-change="handleSelectionChange" @data-change="handleDataChange"></table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import AddOrEdit from './components/AddOrEdit'
import { disableBatch, enableBatch, deleteBatch } from '@/api/elementCombine'
import { deepCopy } from '@/utils/'
import { ArrayFormat } from '@/utils/params-format'
import { ccDict } from '@/api/dataDict'
export default {
  name: 'ElementCombine',
  components: {
    ContentWrap,
    FormContainer,
    SelectForDict,
    SearchSelectPicker,
    AddOrEdit
  },
  data() {
    const validatorLevel = (r, v, c) => {
      if (v === '' || /^\d+$/.test(v)) {
        c()
      } else {
        c(new Error('优先级只能是数字'))
      }
    }
    return {
      enableList: [
        { dictCode: '0', dictName: '停用' },
        { dictCode: '1', dictName: '启用' }
      ],
      formData: {
        combinationCode: '',
        combinationName: '',
        state: '',
        level: '',
        createTime: []
      },
      formRules: {
        level: [{ required: false, validator: validatorLevel, trigger: 'change' }]
      },
      tableConfigTemplete: {
        interfacePath: `/call-center/api/v1/factorFieldCombination/page`,
        tableIndex: 1,
        hideFuncBar: false,
        buttonGroupCode: 'default',
        // order: 'DESC',
        // sort: 'createTime',
        sortersRow: [
          { id: 'createTime', property: 'createTime', direction: 'DESC' },
          { id: 'state', property: 'state', direction: 'DESC' },
          { id: 'level', property: 'level', direction: 'DESC' }
        ],
        setting: []
      },
      setting: [{
        prop: 'level',
        label: '优先级',
        minWidth: 120
      },
      {
        prop: 'state',
        label: '启用状态',
        minWidth: 100,
        formatData(row) {
          return [1, '1'].includes(row.state) ? '启用' : '停用'
        }
      },
      {
        prop: 'createBy',
        label: '创建人',
        minWidth: 100
      },
      {
        prop: 'createTime',
        label: '创建时间',
        minWidth: 140
      }
        // {
        //   prop: 'lastUpdateBy',
        //   label: '最近修改人',
        //   minWidth: 130
        // },
        // {
        //   prop: 'lastUpdateTime',
        //   label: '最近修改时间',
        //   minWidth: 140
        // }
      ],
      combineElementData: [],
      tableData: [],
      selection: [],
      filtersRaw: []
    }
  },
  computed: {
    tableConfig() {
      const t = { ...this.tableConfigTemplete }
      const setting = [
        ...this.genElementColumns(),
        ...this.setting
      ]
      t.setting = setting
      return t
    }
  },
  created() {
    this.getCombineElement()
  },
  methods: {
    getCombineElement() {
      return ccDict('FACTOR_PROPERTY').then(res => {
        this.combineElementData = res.data
      })
    },
    genElementColumns() {
      // const max = Math.max(...this.tableData.map(e => (e.items || []).length), this.combineElementData.length)
      // const max = this.combineElementData.length
      const t = []
      for (let i = 0; i < this.combineElementData.length; i++) {
        t.push(this.elementColumn(i, this.combineElementData[i].sort))
      }
      return t
    },
    elementColumn(i, sort) {
      const n = i + 1
      return {
        prop: `factorName${n}`,
        label: `因子${n}`,
        minWidth: 120,
        formatData: this.formatCombine(sort)
      }
    },
    formatCombine(sort) {
      return row => {
        const items = row.items || []
        const item = items.find(e => e.factorSort === sort)
        return item ? item.factorName : ''
      }
    },
    handleDataChange(data) {
      this.tableData = data.data.records
    },
    resetForm() {
      this.$refs.form.resetFields()
    },
    queryHandle() {
      return this.$refs.form.validate().then(() => {
        const data = deepCopy(this.formData)
        const filtersRaw = [...ArrayFormat(data, {
          combinationCode: 'like',
          combinationName: 'like',
          state: '=',
          level: '=',
          createTime: ['>=', '<=']
        })]
        this.filtersRaw = filtersRaw
        this.refreshTable()
      })
    },
    handleRefresh(type) {
      this.refreshTable(type)
    },
    refreshTable(type) {
      this.selection = []
      this.$nextTick(() => {
        this.$refs.tableBox && this.$refs.tableBox.initTableData(type)
      })
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleUpdateEnable(type) {
      if (!this.singleJudge(this.selection, type === 1 ? '启用' : '停用', false)) {
        return Promise.reject('')
      }
      const t = this.selection.map(e => e.state)
      if (type === 1 && (t.includes(1) || t.includes('1'))) {
        this.$message.warning('所选数据包含【启用】项!')
        return Promise.reject('')
      } else if (type === 0 && (t.includes(0) || t.includes('0'))) {
        this.$message.warning('所选数据包含【停用】项!')
        return Promise.reject('')
      }
      const ajax = type === 1 ? enableBatch : disableBatch
      return ajax(this.selection.map(e => e.id)).then(res => {
        this.$message.success('操作成功!')
        this.refreshTable('onPage')
      })
    },
    handleRemove() {
      if (!this.singleJudge(this.selection, '删除', false)) {
        return Promise.reject('')
      }
      const t = this.selection.map(e => e.state)
      if (t.includes(1) || t.includes('1')) {
        this.$message.warning('所选数据包含【启用】项,不能删除启用项!')
        return Promise.reject('')
      }
      return deleteBatch(this.selection.map(e => e.id)).then(res => {
        this.$message.success('操作成功!')
        this.refreshTable()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.element-combine{
}
</style>
